package com.dragon.mmochat.message;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.model.gang.MmochatGang;
import com.dragon.mmochat.model.gang.MmochatGangMember;
import com.dragon.mmochat.service.MmochatMainService;
import com.skymobi.buffer.SkymobiBuffer;
import com.skymobi.message.SkymobiProtocolMessage;

public class Mmochat_15_4S extends SkymobiProtocolMessage {
	int hallState;
	MmochatGang gang;
	int curPage;

	public Mmochat_15_4S() {
		setMsgCode(MmochatConstant.MSGCODE_MMOCHAT_S_15_4);
	}

	@Override
	protected void encodeBody(SkymobiBuffer out) {
		out.putUnsignedShort(hallState);

		// 帮派成员
		int memberNum = gang.getMembers().size();
		int pageNum = (int) Math.ceil(1.0 * memberNum
				/ MmochatConstant.maxMemberToShowPerPage);
		curPage = Math.max(curPage, 0);
		curPage = Math.min(curPage, pageNum - 1);
		int showMemberNum = Math.min(memberNum - curPage
				* MmochatConstant.maxMemberToShowPerPage,
				MmochatConstant.maxMemberToShowPerPage);
		List<MmochatGangMember> members = null;
		if (showMemberNum > 0) {
			members = new ArrayList<MmochatGangMember>(gang.getMembers()
					.values());
			Collections.sort(members, Collections.reverseOrder());
		}

		out.putShort((short) curPage);
		out.putShort((short) pageNum);
		out.put((byte) showMemberNum);
		int baseIndex = curPage * MmochatConstant.maxMemberToShowPerPage;
		for (int i = 0; i < showMemberNum; i++) {
			MmochatGangMember member = members.get(i + baseIndex);
			out.putInt(member.getRoleId());
			out.putUnsignedShort(member.getBmpId());
			if (MmochatMainService.isPlayerOnline(member.getRoleId())) {
				out.put((byte) 1);
			} else {
				out.put((byte) 0);
			}
			out.putPrefixedString(member.getName(), 1);
			out.putPrefixedString(member.getType().toString(), 1);
			out.putInt(member.getBuildValue());
			out.putInt(member.getCurWeekBuildValue());
		}
	}

	public void setGang(MmochatGang gang) {
		this.gang = gang;
	}

	public void setHallState(int hallState) {
		this.hallState = hallState;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

}
